package thread;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ShengChanZheXiaoFeiZhe {

    static volatile LinkedList<Double> list = new LinkedList<>();
    private static final int count = 10;

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition sheng = lock.newCondition();
        Condition xiao = lock.newCondition();
        Runnable shengchan = () -> {
            while (true) {
                lock.lock();
                while (list.size() >= count) {
                    try {
                        sheng.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                double v = Math.random();
                list.add(v);
                System.out.println("produce:" + v);
                xiao.signalAll();
                lock.unlock();
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable xiaofei = () -> {
            while (true) {
                lock.lock();
                while (list.isEmpty()) {
                    try {
                        xiao.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Double s = list.removeFirst();
                System.out.println("consumer:" + s);
                System.out.println("size:" + list.size());
                sheng.signalAll();
                lock.unlock();
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(shengchan).start();
        //        new Thread(shengchan).start();
        //        new Thread(shengchan).start();
        //        new Thread(xiaofei).start();
        //        new Thread(xiaofei).start();
        new Thread(xiaofei).start();
    }
}
